package my.service;

import com.jfinal.log.Log;
import my.model.User;


/**
 * Created by rajab on 17/4/13.
 */

public class UserService {
    private static final Log log = Log.getLog(UserService.class);

    public enum RegisterResult {
        REGISTER_OK,  //注册成功
        USER_IS_EXISTED, //用户存在
        REGISTER_FAIL // 注册成败
    }

    public RegisterResult register(String username, String password, String nickname) {

        //TODO:完成注册
        //首先判用户是否存在，不存在则new User，并save
        User findUser = findUserByUsername(username);
        if (findUser != null)
            return RegisterResult.USER_IS_EXISTED;
        try {
            User user = new User();
            user.setUsername(username).setPassword(password).setNickname(nickname);
            user.save();
        } catch (Exception ex) {
            log.error("用户注册失败:" + ex.getMessage());
            return RegisterResult.REGISTER_FAIL;
        }
        return RegisterResult.REGISTER_OK;
    }


    public enum LoginResult {
        LOGIN_OK,
        INPUT_INVALID,
        PASSWORD_WRONG,
        USER_NOT_EXIST
    }

    public LoginResult checkLogin(String username, String password) {
        if (username.isEmpty() || password.isEmpty()) {
            return LoginResult.INPUT_INVALID;
        }
        //FIXME:修改为从数据库判断
        User findUser = User.dao.findFirst("SELECT * FROM user where username = ? and password = ?", username, password);
        if (findUser != null) {
            return LoginResult.LOGIN_OK;
        } else {
            return LoginResult.PASSWORD_WRONG;
        }
    }


    // public abstract User createUser(String username, String password, String role);

    public User findUserByUsername(String username) {
        //TODO:根据用户名查找用户

        return User.dao.findFirst("SELECT * FROM user WHERE username = ?", username);
    }
}
